/**
 * Notes: passport模块控制器
 * Date: 2021-03-15 19:20:00 
 */

const BaseController = require('./base_controller.js');
const PassportService = require('../service/passport_service.js');
const contentCheck = require('../../framework/validate/content_check.js');
const timeUtil = require('../../framework/utils/time_util.js');
const util = require('../../framework/utils/util.js');
const config = require('../../config/config.js');

class PassportController extends BaseController {

	/**
	 * 用户登录/注册
	 */
	async login() {
		// 数据校验
		let rules = {
			code: 'must|string|min:1|max:200|name=微信登录code',
			nickName: 'string|max:50|name=用户昵称',
			avatarUrl: 'string|max:200|name=用户头像',
		};

		let input = this.validateData(rules);

		// 使用云函数自动提供的 openid（this._openId 或 this._userId）
		// 这确保了同一微信用户每次登录都是同一个用户ID
		const openid = this._openId || this._userId;
		
		if (!openid) {
			return { success: false, message: '获取用户标识失败' };
		}

		let service = new PassportService();
		return await service.loginWithOpenid(openid, {
			nickName: input.nickName,
			avatarUrl: input.avatarUrl
		});
	}

	/**
	 * 获取我的用户信息
	 */
	async getMyDetail() {
		let service = new PassportService();
		return await service.getMyDetail(this._userId);
	}

	/**
	 * 获取手机号码
	 */
	async getPhone() {
		// 数据校验
		let rules = {
			cloudID: 'must|string|min:1|max:200|name=cloudID',
		};

		let input = this.validateData(rules);

		let service = new PassportService();
		return await service.getPhone(input.cloudID);
	}

	/**
	 * 修改用户资料
	 */
	async editBase() {
		this.ensureAuthenticatedForWrite();
		// 数据校验
		let rules = {
			nickName: 'string|min:1|max:20|name=用户昵称',
			avatarUrl: 'string|max:200|name=用户头像',
			phone: 'string|max:20|name=手机号',
		};

		let input = this.validateData(rules);

		// 内容审核
		await contentCheck.checkTextMultiClient(input);

		let service = new PassportService();
		return await service.editBase(this._userId, input);
	}

	/**
	 * 更新用户余额
	 */
	async updateBalance() {
		this.ensureAuthenticatedForWrite();
		// 数据校验
		let rules = {
			amount: 'must|int|name=金额变化',
		};

		let input = this.validateData(rules);

		let service = new PassportService();
		return await service.updateBalance(this._userId, input.amount);
	}

}

module.exports = PassportController;